package com.example.wm.utils;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CSVUtil {

    public List<Map<String, String>> readCSVFile(InputStream inputStream) {
        List<Map<String, String>> csvDataList = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))) {
            String[] headers = reader.readNext(); // 读取表头
            if (headers == null) {
                throw new IllegalArgumentException("CSV 文件内容为空或格式错误");
            }

            String[] line;
            while ((line = reader.readNext()) != null) {
                Map<String, String> rowMap = new HashMap<>();
                for (int i = 0; i < headers.length; i++) {
                    if (i==0){
                        rowMap.put("成员", line[i].trim());

                    }else{
                        rowMap.put(headers[i].trim(), line[i].trim());

                    }
                }

                csvDataList.add(rowMap);
            }

        } catch (IOException | CsvValidationException e) {
            e.printStackTrace();
            throw new RuntimeException("读取 CSV 文件时发生错误", e);
        }
        return csvDataList;
    }
}